import uuid
from io import BytesIO

from cachetools import TTLCache
from captcha.image import ImageCaptcha

from service.sys.captcha_service import CaptchaService
from util.yaml_util import load_yaml_config

cache_size = load_yaml_config('config/captcha.yaml', 'captcha', 'cache', 'size')
cache_expire = load_yaml_config('config/captcha.yaml', 'captcha', 'cache', 'expire')

# 用于存储验证码的缓存 maxsize 是缓存大小，ttl 是过期时间（秒）
captcha_cache = TTLCache(maxsize=cache_size, ttl=cache_expire)


class CaptchaServiceImpl(CaptchaService):
    def create(self) -> tuple[BytesIO, str]:
        """
        生成验证码
        :return: 图片和验证码文本
        """
        image = ImageCaptcha()
        # 使用UUID生成验证码文本
        captcha_text = str(uuid.uuid4())[:4]
        data = image.generate(captcha_text)
        key = str(uuid.uuid4())
        captcha_cache[key] = captcha_text
        return data, key

    def verify(self, key: str, code: str) -> bool:
        """
        验证码验证
        :param key: 验证码 key
        :param code: 用户输入的验证码文本
        :return: 是否验证通过
        """
        captcha_code = captcha_cache.get(key)
        # 验证码不存在
        if captcha_code is None:
            return False
        # 验证码不匹配
        if captcha_code.lower() != code.lower():
            return False
        # 验证码匹配，删除验证码
        del captcha_cache[key]
        return True
